package com.rshang.ip;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.c3p0.C3p0Plugin;
@SuppressWarnings("rawtypes")
public class IpService {
	private static Log logger = LogFactory.getLog(IpService.class);
	private String jdbcUrl;
	private String user;
	private String password;
	private String czr;
	private int threadLength = 200;
	private final String URL = "http://ip.taobao.com/service/getIpInfo.php?ip=";
	private String txtFilePath;
	
	public IpService(String jdbcUrl, String user, String password, String czr,String txtFilePath) {
		this.jdbcUrl = jdbcUrl;
		this.user = user;
		this.password = password;
		this.czr = czr;
		this.txtFilePath = txtFilePath;
	}
	
	public IpService() {
		this.jdbcUrl = "jdbc:mysql://localhost/statistics?characterEncoding=gbk";
		this.user = "stat";
		this.password = "stat";
		this.czr = "admin";
		this.txtFilePath = "ip.txt";
	}
	public IpService(String txtFilePath) {
		this.jdbcUrl = "jdbc:mysql://localhost/statistics?characterEncoding=gbk";
		this.user = "stat";
		this.password = "stat";
		this.czr = "admin";
		this.txtFilePath = txtFilePath;
	}
	
	
	public List getIpList() throws Exception
	{
		List ipList = new ArrayList();
		String filename = System.getProperty("user.dir") +"/"+ txtFilePath;
		System.out.println(filename);
		File file = new File(filename);
		
		//InputStreamReader reader = new InputStreamReader(IpService.class.getResourceAsStream(txtFilePath));// 建立一个输入流对象reader 
		InputStreamReader reader = new InputStreamReader(new FileInputStream(file));// 建立一个输入流对象reader  
        BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机
        String line = br.readLine();
        Map map = null;
        String[] ip_arr = null;
        while(line!=null)
        {
        	if(!line.isEmpty())
        	{
	        	ip_arr = line.trim().split("-");
	        	map = new HashMap();
	        	map.put("begin", ip_arr[0]);
	        	map.put("end", ip_arr[1]);
	        	ipList.add(map);
        	}
        	line = br.readLine();
        }
        if (br != null) 
        {
        	br.close();
        }
        return ipList;
	}
	
	public boolean getTaoBaoIp(List ip) throws Exception
	{
		C3p0Plugin cp = new C3p0Plugin(jdbcUrl, user, password);
        cp.start();
        
        ActiveRecordPlugin arp = new ActiveRecordPlugin(cp);
        //arp.setShowSql(true);
        arp.start();
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(10000);
        cm.setDefaultMaxPerRoute(1000);
        cm.closeExpiredConnections();
        
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();
        HttpGet httpGet = null;
        
        for(int i=0;i<ip.size();i++)
        {
	        Map ipMap = (Map) ip.get(i);
	        String[] beginIp_arr = ((String)ipMap.get("begin")).split("\\.");
			String[] endIp_arr = ((String)ipMap.get("end")).split("\\.");
			
			String ip_begin = String.format("%03d.%03d.%03d.%03d", Integer.parseInt(beginIp_arr[0]), Integer.parseInt(beginIp_arr[1]),Integer.parseInt(beginIp_arr[2]), Integer.parseInt(beginIp_arr[3]));
			String ip_end = String.format("%03d.%03d.%03d.%03d", Integer.parseInt(endIp_arr[0]), Integer.parseInt(endIp_arr[1]),Integer.parseInt(endIp_arr[2]), Integer.parseInt(endIp_arr[3]));
			//this.logger.info("ip:"+ip_begin+"~"+ip_end);
			System.out.println("ip:"+ip_begin+"~"+ip_end);
			String beginIp = beginIp_arr[0];
			String endIp = endIp_arr[0];
			IpThread[] threads = new IpThread[threadLength];
			
			int threadCount = 0;
			int time = 0;
			boolean breaks = false;
			for (int a = Integer.parseInt(beginIp); a <= Integer.parseInt(endIp); a++) 
			{
				
				for (int b = 0; b <= 255; b++) 
				{
				   if(breaks)
				   {
					  break;
				   }
				   if(time==0)
				   {
					   b = Integer.parseInt(beginIp_arr[1]);
				   }
					for (int c = 0; c <= 255; c++) 
					{
					if(breaks)
					   {
						  break;
					   }
					   if(time==0)
					   {
						   c = Integer.parseInt(beginIp_arr[2]);
					   }
						
						for (int d = 0; d <= 255; d++) 
						{
						  if(breaks)
						   {
							  break;
						   }
						   if(time==0)
						   {
							   d = Integer.parseInt(beginIp_arr[3]);
							   time++;
						   }
							String ips = String.format("%d.%d.%d.%d", a, b,c, d);
							//this.logger.info(ip_end+":::"+(String.format("%03d.%03d.%03d.%03d", a, b,c, d))+" - "+ip_end.equals(String.format("%03d.%03d.%03d.%03d", a, b,c, d)));
							if(ip_end.equals(String.format("%03d.%03d.%03d.%03d", a, b,c, d)))
							{
								breaks = true;
								break;
							}
							if(Double.parseDouble((String.format("%03d.%03d.%03d.%03d", a, b,c, d)).replaceAll("\\.", ""))>=Double.parseDouble(ip_begin.replaceAll("\\.", "")))
							{
								httpGet = new HttpGet(URL+ips);
								//this.logger.info("ip:"+ips);
								if(threadCount==threadLength)
								{
									//this.logger.info("begin ip:"+ips);
									// start the threads
									for (int j = 0; j < threads.length; j++) {
									    threads[j].start();
									}
	
									// join the threads
									for (int j = 0; j < threads.length; j++) {
									    threads[j].join();
									}
									threads = new IpThread[threadLength];
									threadCount = 0;
								}
								if(threadCount<threadLength)
								{
									threads[threadCount++] = new IpThread(httpClient,httpGet,ips,czr);
								}
							}
						}
					}
				}
			}
			
        }
        httpClient.close();
        return true;
	}
	
	public static void main(String[] args)  {
		IpService service = new IpService(args[0]);
		try {
			service.getTaoBaoIp(service.getIpList());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
